/**
 * 结账 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0002.CA.CloseAccMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 70,
        header: false,
        collapsible: true,
        collapseMode: "mini",
        border: 0,
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        border: 0,
        ...PSI.Const.BODY_PADDING,
        items: [
          {
            region: "west",
            border: 0,
            layout: "fit",
            width: 860,
            items: me.getCompanyGrid(),
            split: true,
          }, {
            region: "center",
            border: 0,
            layout: "fit",
            items: me.getMainGrid(),
          }]
      }]
    });

    me.callParent(arguments);

    me.panelQueryCmp = PCL.getCmp(me.buildId(me, "panelQueryCmp"));

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = me.panelQueryCmp;
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.refreshCompanyGrid();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];
    let list = [];

    result.push({
      iconCls: "PSI-tb-new",
      text: "结转损益",
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler: me._onLossAndProfit,
    }, "-", {
      text: "企业所得税账务处理",
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler: me._onCalcIncomeTax,
      tooltip: me.buildTooltip("手工计算出季度预缴额后，由此生成凭证并记账"),
    }, "-", {
      text: "计提固定资产折旧",
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler() {
        me.focus();
        window.open(me.URL("Home/MainMenu/navigateTo/fid/2501"));
      },
      tooltip: me.buildTooltip("打开自动生成凭证模块去处理计提固定资产折旧"),
    }, {
      text: "计提职工薪酬",
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler() {
        me.focus();
        window.open(me.URL("Home/MainMenu/navigateTo/fid/2501"));
      },
      tooltip: me.buildTooltip("打开自动生成凭证模块去处理计提职工薪酬"),
    }, "-", {
      text: "完成结账",
      ...PSI.Const.BTN_STYLE,
      scope: me,
      handler: me._onCloseAcc,
    });

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("/Home/Help/index?t=accClose"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["->",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
  * 查询条件
  * 
  * @private
  */
  getQueryCmp() {
    const me = this;

    const modelName = me.buildModelName(me, "QueryOrg");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "name"]
    });

    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:6px;color:#595959;display:inline-block'>结账</h2>
                &nbsp;&nbsp;<span style='color:#8c8c8c'>月底结账</span>
                <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:40px'>&nbsp;</div>
                `
    }, { xtype: "container" }, {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          me.panelQueryCmp.collapse();
        },
        scope: me
      }]
    },];
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;

    const result = {};

    return result;
  },

  /**
 * @private
 */
  getCompanyGrid() {
    const me = this;
    if (me._companyGrid) {
      return me._companyGrid;
    }

    const modelName = me.buildModelName(me, "GLPeriod_Company");

    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "orgType", "currentPeriod", "detailClosed", "glClosed"]
    });

    me._companyGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      header: {
        height: 30,
        title: me.formatGridHeaderTitle(me.toTitleKeyWord("核算组织机构"))
      },
      columnLines: true,
      columns: [{
        header: "编码",
        dataIndex: "code",
        menuDisabled: true,
        sortable: false,
        width: 70
      }, {
        header: "组织机构名称",
        dataIndex: "name",
        width: 300,
        menuDisabled: true,
        sortable: false,
        renderer(value) {
          return me.toAutoWrap(value);
        }
      }, {
        header: "组织机构性质",
        dataIndex: "orgType",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "当前会计期间",
        dataIndex: "currentPeriod",
        width: 100,
        menuDisabled: true,
        sortable: false,
        align: "center",
      }, {
        header: "明细分类账已关账",
        dataIndex: "detailClosed",
        width: 140,
        menuDisabled: true,
        sortable: false,
        align: "center",
      }, {
        header: "总分类账已关账",
        dataIndex: "glClosed",
        width: 140,
        menuDisabled: true,
        sortable: false,
        align: "center",
      },],
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onCompanyGridSelect,
          scope: me
        }
      }
    });
    return me._companyGrid;
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;
    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "PeriodGrid");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "year", "month", "glClosed", "detailClosed", "periodClosed",
        "memo"
      ]
    });

    const defaultColsProp = {
      menuDisabled: true,
      sortable: false,
      draggable: false
    };

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("会计期间")
      },
      emptyText: me.toEmptyText("尚未初始化本年度会计期间"),
      columnLines: true,
      columns: {
        defaults: defaultColsProp,
        items: [{
          header: "年",
          dataIndex: "year",
          width: 60,
          align: "center"
        }, {
          header: "月",
          dataIndex: "month",
          width: 60,
          align: "center"
        }, {
          header: "",
          dataIndex: "memo",
          width: 100,
        }, {
          header: "明细分类账已关账",
          dataIndex: "detailClosed",
          width: 130,
          align: "center",
        }, {
          header: "总分类账已关账",
          dataIndex: "glClosed",
          width: 120,
          align: "center",
        }, {
          header: "本期间已结账",
          dataIndex: "periodClosed",
          width: 120,
          align: "center"
        }]
      },
      store: PCL.create("PCL.data.Store", {
        model: modelName,
        autoLoad: false,
        data: []
      })
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  refreshCompanyGrid() {
    const me = this;
    const el = PCL.getBody();
    const store = me.getCompanyGrid().getStore();
    el.mask(PSI.Const.LOADING);
    const r = {
      url: me.URL("SLN0002/CA/companyList"),
      callback(options, success, response) {
        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (store.getCount() > 0) {
            me.getCompanyGrid().getSelectionModel().select(0);
          }
        }

        el.unmask();
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  _onLossAndProfit() {
    const me = this;

    const item = me.getCompanyGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const company = item[0];

    const period = company.get("currentPeriod");
    if (!period) {
      me.showInfo(`组织机构: <span style='color:red'>${company.get("name")}</span> 尚未初始化会计期间`);
      return;
    }

    const info = `组织机构: <span style='color:red'>${company.get("name")}</span> 
                  <br/>
                  请确认是否对会计期间<span style='color:green'>${period}</span>做结转损益处理?`;
    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在操作中...");
      const r = {
        url: me.URL("SLN0002/CA/actionLossAndProfit"),
        params: {
          companyId: company.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成结转损益操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  /**
   * @private
   */
  _onCalcIncomeTax() {
    const me = this;
    me.showInfo("TODO")
  },

  /**
   * @private
   */
  _onCloseAcc() {
    const me = this;

    const item = me.getCompanyGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const company = item[0];

    const period = company.get("currentPeriod");
    if (!period) {
      me.showInfo(`组织机构: <span style='color:red'>${company.get("name")}</span> 尚未初始化会计期间`);
      return;
    }

    const info = `组织机构: <span style='color:red'>${company.get("name")}</span> 
                  <br/>
                  请确认是否对会计期间<span style='color:green'>${period}</span>做结账处理?`;
    const funcConfirm = () => {
      const el = PCL.getBody();
      el.mask("正在操作中...");
      const r = {
        url: me.URL("SLN0002/CA/actionCloseAcc"),
        params: {
          companyId: company.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.tip("成功完成结账操作", true);
              me.refreshCompanyGrid();
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      };
      me.ajax(r);
    };

    me.confirm(info, funcConfirm);
  },

  _onCompanyGridSelect() {
    const me = this;

    me.getMainGrid().setTitle(me.formatGridHeaderTitle("会计期间"));
    const item = me.getCompanyGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const company = item[0];

    const title = me.toTitleKeyWord(company.get("name")) + " - 会计期间";
    me.getMainGrid().setTitle(me.formatGridHeaderTitle(title));

    const grid = me.getMainGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);

    const r = {
      url: me.URL("SLN0002/GLPeriod/periodList"),
      params: {
        companyId: company.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
        }

        el?.unmask();
      }
    };
    me.ajax(r);
  },
});
